import React, { useState, useEffect } from "react";
import styled from "@emotion/styled";
import { motion, AnimatePresence } from "framer-motion";
import {
  FiX,
  FiAlertCircle,
  FiInfo,
  FiCheck,
  FiAlertTriangle,
} from "react-icons/fi";
import { MessageType } from "../tools/common-types";
import {
  duration as animationDuration,
  easing,
  motionEasing,
  radius,
  spacing,
} from "../utils/design-tokens";

// 样式定义
const AlertContainer = styled(motion.div)<{ $type: string }>`
  width: 100%;
  position: relative;
  display: flex;
  align-items: flex-start;
  padding: ${spacing["4"]} ${spacing["5"]};
  border-radius: ${radius.lg};
  margin-bottom: ${spacing["4"]};
  background-color: ${({ $type }) =>
    $type === "success"
      ? "var(--success-bg)"
      : $type === "info"
      ? "var(--info-bg)"
      : $type === "warning"
      ? "var(--warning-bg)"
      : "var(--error-bg)"};
  border-left: 4px solid
    ${({ $type }) =>
      $type === "success"
        ? "var(--success-border)"
        : $type === "info"
        ? "var(--info-border)"
        : $type === "warning"
        ? "var(--warning-border)"
        : "var(--error-border)"};
  color: var(--text-primary);

  @media (max-width: 768px) {
    padding: ${spacing["3"]} ${spacing["4"]};
  }
`;

const AlertIconWrapper = styled.div<{ $type: string }>`
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: ${spacing["3"]};
  flex-shrink: 0;
  color: ${({ $type }) =>
    $type === "success"
      ? "var(--success-color)"
      : $type === "info"
      ? "var(--info-color)"
      : $type === "warning"
      ? "var(--warning-color)"
      : "var(--error-color)"};
`;

const AlertContent = styled.div`
  flex: 1;
  min-width: 0;
`;

const AlertTitle = styled.h4`
  margin: 0 0 ${spacing["1"]};
  font-size: 1rem;
  font-weight: 600;
  line-height: 1.4;
`;

const AlertMessage = styled.p`
  margin: 0;
  font-size: 0.95rem;
  color: var(--text-secondary);
  line-height: 1.5;
  word-break: break-word;
`;

const CloseButton = styled.button`
  background: none;
  border: none;
  color: var(--text-tertiary);
  cursor: pointer;
  padding: ${spacing["1"]};
  margin-left: ${spacing["2"]};
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: ${radius.full};
  transition: all ${animationDuration.fast}ms ${easing.ease};
  flex-shrink: 0;

  &:hover {
    background-color: var(--bg-tertiary);
    color: var(--text-primary);
  }

  &:active {
    transform: scale(0.95);
  }
`;

// 组件接口
export interface AlertProps {
  type: MessageType;
  title?: string;
  message: string;
  closable?: boolean;
  duration?: number | null;
  onClose?: () => void;
}

// Alert组件
export const Alert: React.FC<AlertProps> = ({
  type = "info",
  title,
  message,
  closable = true,
  duration = null,
  onClose,
}) => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    if (!duration) return;

    const timer = setTimeout(() => {
      setVisible(false);
      onClose?.();
    }, duration);

    return () => clearTimeout(timer);
  }, [duration, onClose]);

  const handleClose = () => {
    setVisible(false);
    onClose?.();
  };

  const getIcon = () => {
    switch (type) {
      case "success":
        return <FiCheck size={22} />;
      case "info":
        return <FiInfo size={22} />;
      case "warning":
        return <FiAlertTriangle size={22} />;
      case "error":
        return <FiAlertCircle size={22} />;
      default:
        return <FiInfo size={22} />;
    }
  };

  return (
    <AnimatePresence>
      {visible && (
        <AlertContainer
          $type={type}
          initial={{ opacity: 0, y: -10, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{
            opacity: 0,
            y: -10,
            scale: 0.95,
            height: 0,
            marginBottom: 0,
            overflow: "hidden",
          }}
          transition={{
            duration: animationDuration.fast / 1000,
            ease: motionEasing.spring,
          }}
          layout
        >
          <AlertIconWrapper $type={type}>{getIcon()}</AlertIconWrapper>

          <AlertContent>
            {title && <AlertTitle>{title}</AlertTitle>}
            <AlertMessage>{message}</AlertMessage>
          </AlertContent>

          {closable && (
            <CloseButton onClick={handleClose} aria-label="关闭提示">
              <FiX size={18} />
            </CloseButton>
          )}
        </AlertContainer>
      )}
    </AnimatePresence>
  );
};

export default Alert;
